<?php
// 获取JSON数据
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

// 获取表单提交的数据
$username = $data['username'];
$password = $data['password'];

// 连接到数据库
$servername = "localhost";
$usernameDB = "root";
$passwordDB = "root";
$dbname = "fish";

$conn = new mysqli($servername, $usernameDB, $passwordDB, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 查询用户名是否已存在
$sql = "SELECT * FROM user WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

// 判断查询结果
if ($result->num_rows > 0) {
    echo json_encode(['status' => 'error', 'message' => '用户名已存在']);
} else {
    // 将新用户插入到数据库
    // $password = md5($password); // 使用md5加密密码
    $sql = "INSERT INTO user (username, password, admin) VALUES (?, ?, 0)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();

    // 判断是否插入成功
    if ($stmt->affected_rows > 0) {
        echo json_encode(['status' => 'success', 'message' => "注册成功，欢迎您，" . $username . "!"]);
    } else {
        echo json_encode(['status' => 'error', 'message' => "注册失败，请重试。"]);
    }
}

// 关闭数据库连接
$stmt->close();
$conn->close();
?>
